package com.thememaker.lockstyle;

import com.thememake.Constants;
import com.thememake.entity.ThemeFileInfo;
import com.thememake.ui.Toast;
import com.thememaker.lockstyle.bean.Lockscreen;
import com.thememaker.lockstyle.bean.ui.BaseView;
import javafx.application.Platform;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author yiyi.zheng 2018/7/6
 * 中间部分下方文本区域
 */
public class LockstyleCenterBottomArea {
    private final Stage stage;
    private final LockstyleShowUtils lockstyleShowUtils;
    private final Button editTextAreaBtn;
    private TextArea editTextArea;
    private ThemeFileInfo themeFileInfo;
    private Path lockscreenPath;
    private int screen_height = 1920;
    private int screen_width = 1080;
    private Document document;
    private Lockscreen lockscreen;
    private String xmlStr;
    private LinkedHashMap<String, BaseView> map;
    private Path xmlPath;
    private long lastEditTime;
    private ScheduledThreadPoolExecutor executorService;

    public int getScreen_height() {
        return screen_height;
    }

    public void setScreen_height(int screen_height) {
        this.screen_height = screen_height;
        updateTextAreaView(null);
    }

    public LockstyleCenterBottomArea(TextArea editTextArea, Button editTextAreaBtn, ThemeFileInfo themeFileInfo, Path lockscreenPath, Stage stage, LockstyleShowUtils lockstyleShowUtils) {
        this.editTextArea = editTextArea;
        this.editTextAreaBtn = editTextAreaBtn;
        this.themeFileInfo = themeFileInfo;
        this.lockscreenPath = lockscreenPath;
        this.stage = stage;
        this.lockstyleShowUtils = lockstyleShowUtils;
        executorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
        updateTextAreaView(null);
    }

    public void updateTextAreaView(BaseView baseView) {
//        editTextArea.setText(JSONObject.toJSONString(baseView));
        xmlPath = Paths.get(lockscreenPath.toString(), "manifest.xml");
        try {
            if (themeFileInfo.getThemeType().equals(Constants.OPPO)) {
                switch (screen_height) {
                    case 2160:
                        xmlPath = Paths.get(lockscreenPath.toString(), "2x1", "manifest.xml");
                        break;
                    case 2280:
                        xmlPath = Paths.get(lockscreenPath.toString(), "19x9", "manifest.xml");
                        break;
                    case 2340:
                        xmlPath = Paths.get(lockscreenPath.toString(), "13x6", "manifest.xml");
                        break;
                    default:
                        xmlPath = Paths.get(lockscreenPath.toString(), "manifest.xml");
                        break;
                }
            }
            xmlStr = readToString(xmlPath.toString());
            editTextArea.setText(xmlStr);
            editTextArea.textProperty().addListener((observable, oldValue, newValue) -> {
                editTextArea.setId("diy-textarea");
                lastEditTime = System.currentTimeMillis();
                executorService.scheduleAtFixedRate(() -> {
                    if (System.currentTimeMillis() - lastEditTime >= 2000) {
                        save(newValue);
                    } else {
                    }
                }, 2, 5, TimeUnit.SECONDS);
            });
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(stage, e.getMessage(), 2000);
        }

    }

    private boolean notSave = false;

    public void save(String newValue) {
        try {
            notSave = false;
            StringReader sr = new StringReader(newValue);
            InputSource is = new InputSource(sr);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            document = builder.parse(is);
            lockscreen = LockstylePaserUtils.paserLockScreenXml(document);
            map = lockscreen.getLockScreenViewMap();
        } catch (Exception e) {
            notSave = true;
            editTextArea.setId("textfield-error");
        } finally {
            executorService.shutdown();
            executorService = new ScheduledThreadPoolExecutor(1,
                    new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
        }
        editTextAreaBtn.setOnAction(event -> {
            if (!notSave) {
                LockstylePaserUtils.saveLockScreenXml(themeFileInfo,document, lockscreen, xmlPath.toFile());
                updateTextAreaView(null);
                Platform.runLater(() -> {
                    lockstyleShowUtils.showLockscreen();
                });
            } else {
                Toast.makeText(stage, "请修改错误", 200);
            }
        });
    }

    public String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
